Skip to main content

Interview Questions

See the .NET folder for .NET questions and CompSci folder for general Computer Science/Theory questions

Lists (no sort - C#/>NET mixed):

https://www.devteam.space/hiring-interview-tips/c-interview-questions-and-answers/ https://www.fullstack.cafe/blog/c-sharp-interview-questions https://www.interviewbit.com/dot-net-interview-questions/

Note: These questions are only loosely organized. You might see essentially the same question back to back, this is because I just grouped like things together without paying close attention to what is being asked... maybe one day I'll refine the list.

C# Questions

Types

What is the Common Type System?

common type system

Explain the differences between value type and reference type.

The main differences between value type and reference type are given below:

  • A Value Type holds the actual data directly within the memory location and a reference type contains a pointer which consists of the address of another memory location that holds the actual data.
  • Value type stores its contents on the stack memory and reference type stores its contents on the heap memory.
  • Assigning a value type variable to another variable will copy the value directly and assigning a reference variable to another doesn’t copy the value, instead, it creates a second copy of the reference.
  • Predefined data types, structures, enums are examples of value types. Classes, Objects, Arrays, Indexers, Interfaces, etc are examples of reference types.

Boxing:

value type -> reference type Boxing is implicit.

Unboxing:

reference type -> value type. Unboxing is explicit.

An example is given below to demonstrate boxing and unboxing operations:

int a = 10;      // a value type
object o = a; // boxing
int b = (int)o; // unboxing

Reflection

Reflection objects are used for creating type instances and obtaining type information at runtime.

The classes in the System.Reflection namespace gives access to the metadata of a running program.

Exception Handling

Throw vs Throw Ex

Throw maintains the complete error stack trace Throw ex resets the error stack trace

Handling Exceptons in finally block

exceptions in finally block

Arrays & Lists

What is a jagged Array?

An array of arrays/2D array (arrays can be varying lengths)

string [][] jaggedArray = new string[3][];

jaggedArray[0] = new string[3]
jaggedArray[1] = new string[5]
jaggedArray[2] = new string[2]

Can you store different types in an array?

Yes, using an object array or System.Collections.ArrayList (b/c all types inherit from the object type)

Object Array

object[] arr = new object[3];
arr[0] = 12;
arr[1] = "mystr";

//Even complex types
class Customer
{
public int ID {get; set;}
public string name {get; set;}
}

var c = new Customer
c.ID = 1;
c.Name = "Bill"

arr[2] = c;

System.Collections.ArrayList

using System.Collections;
var arrList = new ArrayList();
arrList.Add(101);
arrList.Add("C#");

//Same for complex types

Functions & Methods

Pk_ToDo Update

Ref & Out Parameters

Source

Allow you to pass a variable by reference to a method. ref - requires variable initialization out- only requires variable declaration

Classes

Constructors

A constructor is a special method of the class that contains a collection of instructions and gets automatically invoked when an instance of the class is created.

There are 5 types of constructors in C#, as given below:

  • Default Constructor- It is without any parameters.
  • Parameterized Constructor- It has one parameter.
  • Copy Constructor- It creates an object by copying variables from another object. Show Example
  • Static Constructor- It is created using a static keyword and will be invoked only once for all of the instances of the class.
  • Private Constructor- It is created with a private access modifier and does not allow other classes to derive from this class or create an instance of it.

The default constructor access modifier is Public.

And you can prove this.

Youtube Video PK_ToUpdate:Embed Video

Destructors

Source

In c#, Destructor is a special method of a class, and it is used in a class to destroy the object or instances of classes. The destructor in c# will invoke automatically whenever the class instances become unreachable.

class User 
{
// Destructor
~User()
{
// your code
}
}

Partial Classes

Source

Rules to Implement Partial Class

In c#, we need to follow certain rules to implement a partial class in our applications.

  • To split the functionality of class, structure, interface, or a method over multiple files, we need to use partial keyword and all files must be available at compile time to form the final type.

  • The partial modifier can only appear immediately before the keywords class, struct or interface.

  • All parts of partial type definitions must be in the same namespace or assembly.

  • All parts of partial type definitions must have the same accessibility, such as public, private, etc.

  • If any partial part is declared as abstract, sealed, or base, then the whole type is considered abstract or sealed or base based on the defined type.

  • In c#, different parts can have different base types, but the final type will inherit all the base types.

  • Nested partial types are allowed in partial type definitions.

Abstract Classes

Abstract Classes

Abstract classes cannot be sealed b/c that is a contradiction:

  • sealed: class cannot be inherited from
  • abstract: class must be inherited from

Abstract classes MAY contain non-abstract members

public abstract class Customer
{
public void Print(){ ... }
}

*this is a difference between abstract classes and interfaces. Interfaces cannot contain any implementations

When/Why use an Abstract Class?

Alt: Give an example of when we could use an abstract class

tl;dr: When we want to extract functionality from common classes into a base class AND we don't want the base class to be instantiated.

Common functionality between these classes causes a maintenance issue (you need to update both)

When to use an abstract class

So we could extract the common functionality into:

  1. A concrete base class (*see reason NOT to do this below)
  2. An abstract class

If we use a concrete base class:

  • Then someone could instantiate using that base class and call virtual methods

  • There are no compilation errors but there are runtime errors

  • So mark it as abstract (Now the base class can't be instantiated)

  • And add the common methods to the abstract class, so that all classes which inherit MUST provide the methods implementation

  • Also mark these abstract because you don't provide the implementation in base class

    Can we use normal methods in abstract class?

Abstract Class - Can it have a constructor?

YES! Abstract Class Can Have Constructor

When to use:

  • To initialise fields of the abstract class
  • To initialise certain fields of the abstract class before the instantiation of child class
  • To execute code that is relevant for every child class

Virtual vs Abstract methods

Virtual methods can have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

Test Your Knowledge

An Abstract Class has a default implementation for a method. The method's default implementation is needed in some class but not in some other class. How can you achieve this?

Mark the method as Virtual Virtual Method- Derived classes are free to use the default implementation or provide their own implementation (with override keyword)

public abstract class Database
{
public virtual void connect(){...}
}

public class SqlServer : Database
{
public override void connect(){ ... }
}

public class MySql : Database {}

class Program{
public static void Main()
{
MySql mysql = new MySql();
mysql.connect();

SqlServer sqlServ = new SqlServer();
sqlServ.connect();
}
}

Interfaces

Interfaces

Interfaces Can only contain declarations, no implementations

//This results in compile time error b/c Print has an implementation
interface ICustomer
{
void Print()
{
Console.WriteLine("Hello")
}
}

Interface Members are public by default and Not allowed to have explicit access modifiers

Interfaces can NOT have fields --- i.e. int ID;

Interfaces can inherit from other interfaces

interface ICustomer : IPerson {}

Class implementing/inheriting the interface must implement all methods, including the methods inherited

interface IPerson {
void DoStuff();
}

interface ICustomer : IPerson {
void Print()
}

class Customer : ICustomer{
public void Print() { ...Implementation... }
public void DoStuff() { ...Implementation... }
}

Classes can inherit multiple interfaces (but not multiple classes)

class Customer : ICustomer, ISomethingElse, IAnotherInterface

We cannot create an instance of an interface, but an interface reference variable can point to a derived class object

ICustomer cust = new Customer();

How do you make an interface the default?

To make an interface the default, you implement it normally and implement the other interfaces explicitly. T1 is default b/c it is implemented normally (without T1. )

interface T1 
{
void InterfaceMethod();
}
interface T2
{
void InterfaceMethod();
}
public class SkyNetBot : T1, T2
{

public void InterfaceMethod(){ ... }

void T2.InterfaceMethod(){ ... }
}

Explicit (Multiple) Interfaces Implementation

When you have a class that implements multiple interfaces with identical method signatures, how does the class know which method is being called?

It doesn't, so you must explicitly implement the interfaces methods in the class, and typecast the reference variable when calling the method.

interface T1
{
void InterfaceMethod();
}

interface T12
{
void InterfaceMethod();
}

public class SkyNetBot : T1, T2
{
//Explicit Implementations
void T1.InterfaceMethod(){ ... }
void T2.InterfaceMethod(){ ... }
}


SkyNetBot Arnie = new SkyNetBot();

Arnie.InterfaceMethod() <- Compiler Error

//TypeCast Arnie ref variable to T1
((T1)Arnie).InterfaceMethod()

//Or create it this way
T1 Arnie = new SkyNetBot();
Arnie.InterfaceMethod()

To make an interface the default, you implement it normally and implement the other interfaces explicitly.

Abstract Classes vs Interfaces

Use an abstract class to provide some concrete implementation but not allow instantiation. An abstract class is DRYer than an interface if there's a concrete implementation that's identical in all implementing classes.

Interface: contract only, no implementation, no instantiation Abstract class: contract, some/none implementation, no instantiation Class: contract, implementation, instantiation Source

Membership/Implementation

Abstract classes can have implementation for some of it's members, interfaces cannot.

Abstract classes can have fields, interfaces cannot.

Inheritance

Interfaces can only inherit from interfaces. Abstract classes can inherit from both interfaces and abstract classes

A class can inherit from multiple interfaces, but not multiple classes (including abstract classes)

Access Modifiers

Abstract class members can have access modifiers, interface members cannot. (b/c the derived class must implement all members of an interface)

Abstract class members are private by default, interface members are public (by default and always).

Another Chart I Found to Show the Diff:

Abstract ClassInterface
Can declare properties, events, methods, and fields as well.Fields cannot be declared using interfaces.
Provides the partial implementation of functionalities that must be implemented by inheriting classes.Used to declare the behavior of an implementing class.
Different kinds of access modifiers like private, public, protected, etc. are supported.Only public access modifier is supported.
It can contain static members.It does not contain static members.
Multiple inheritances cannot be achieved.Multiple inheritances are achieved.
Can inherit from both interfaces or abstract classesCan only inherit from interfaces

More Concepts

What are Generics?

Source

Generic classes and methods combine reusability, type safety, and efficiency in a way that their non-generic counterparts cannot.

What is a delegate?

A delegate is a type that encapsulates a reference to a method.

Delegate objects can then be passed to code which calls the method according to the method signature, meaning the developer doesn't have to know at compile time which method is being invoked.

A delegate can contain references to a single method or multiple methods. Delegates are similar to function pointers in C/C++ and have the advantage of being type-safe.

What is a Predicate?

Source

In c#, Predicate is a built-in generic delegate, and it is useful to validate

whether the input parameter meets the specified condition or not

and it’s same as Func and Action delegates to hold the reference of one or more methods.

only accepts one input parameter and returns a Boolean value

public delegate bool Predicate<in T>(T arg);

MISC Questions

Int vs Int32

Both create a 32-bit integer! int is just shorthand.

Int vs Int32

*Enums cannot inherit Int32

IS vs AS Keyword

The diff is in the return

IS vs AS

systems.StringBuilder vs system. string?

System.string is immutable and fixed-length, whereas StringBuilder is mutable and variable length. The size of the .string cannot be changed, but that of the stringbuilder can be changed.

Reverse Each Word in a string

Using LINQ:

string inputString = 'one two three four five';
string resStr = string.Join(' ', inputString
.Split(' ')
.Select( x => new String(x.Reverse().ToArray()));
);